package edu.utdallas.taskExecutor;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TaskExecutorImpl implements TaskExecutor{
    
    // Create a static object for the sub classes to use
    static TaskExecutorImpl taskExecutor;
    
    // Holds threads executing the tasks
    ArrayList<TaskRunner> taskRunners;
    
    // Holds tasks waiting to be exectued
    BlockingQueueComet taskQueue;
    
    public TaskExecutorImpl() {
        
    }
    
    public TaskExecutorImpl(int num) {
        
        // Initialize taskQueue
        taskQueue = new BlockingQueueComet(num);
        
        // Create num TaskRunners, add to ArrayList
        taskRunners = new ArrayList();
       
        while(num > 0) {
            StringBuilder sb = new StringBuilder();
            sb.append(num);
            TaskRunner taskRunner = new TaskRunner(sb.toString());
            taskRunners.add(taskRunner);
            num--;
        }
        
        // Set the static object to this instance of TaskExecutor
        taskExecutor = this;
        
        // Start the threads
        for(TaskRunner taskRunner: taskRunners) {
            Thread insertThread = new Thread(taskRunner);
            insertThread.start();
        }
    }
    
    @Override
    public void addTask(Task task) {
        try {
            // Add tasks to blocking queue, blocks if full
            taskExecutor.taskQueue.put(task);
        } catch (InterruptedException ex) {
            Logger.getLogger(TaskExecutorImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public Object getTask() throws InterruptedException {
       return taskExecutor.taskQueue.take();
    }
}
